<template>
	<jk-dialog
		v-model="showDialog"
		title="工艺任务"
		width="1100px"
		:show-content-loading="showLoading"
		:confirm-btn-loading="confirmBtnLoading"
		append-to-body
		@on-cancel="onVisibleChange(false)"
		@on-visible-change="onVisibleChange"
		@on-confirm="onConfirmBtn"
	>
		<el-form ref="ruleForm" :model="ruleForm" :rules="rules" label-width="110px" :show-message="false">
			<div ref="box1">
				<el-row class="flex-start-center-wrap">
					<el-col :span="8">
						<el-form-item class="margin-bottom-10" label="机台:">
							<span class="read-only-2 technology-task-form-val">{{ dataId ? dataId.map(x => x.machineCode).join() : '' }}</span>
						</el-form-item>
					</el-col>
					<el-col :span="8">
						<el-form-item class="margin-bottom-10" label="品种:">
							<span class="read-only-2 technology-task-form-val">{{ ruleForm.productName }}</span>
						</el-form-item>
					</el-col>
					<el-col :span="8">
						<el-form-item class="margin-bottom-10" label="批号:">
							<span class="read-only-2 technology-task-form-val">{{ ruleForm.batchCode }}</span>
						</el-form-item>
					</el-col>
					<el-col :span="8">
						<el-form-item class="margin-bottom-10" label="生产通知单:">
							<span class="read-only-2 technology-task-form-val">{{ ruleForm.prdNoticeCode }}</span>
						</el-form-item>
					</el-col>
					<!--前纺-10米价不必填-->
					<!--<el-col v-show="isFront()" :span="12">
						<el-form-item v-if="isFront()" class="margin-bottom-4" label="10米价:">
							<jk-number-input v-model="ruleForm.tenPrice" size="small" placeholder="10米价" class="width-100-percent"></jk-number-input>
						</el-form-item>
					</el-col>
					<el-col v-show="!isFront()" :span="12">
						<el-form-item v-if="!isFront()" class="margin-bottom-4" label="10米价:" prop="tenPrice">
							<jk-number-input v-model="ruleForm.tenPrice" size="small" placeholder="10米价" class="width-100-percent"></jk-number-input>
						</el-form-item>
					</el-col>-->
					<el-col :span="8">
						<el-form-item class="margin-bottom-4" label="工艺单:" prop="specSheetId">
							<jk-input v-model="ruleForm.specSheetCode" readonly placeholder="在底部的表格中选择" size="small" class="width-100-percent"></jk-input>
						</el-form-item>
					</el-col>
				</el-row>
				<!--<el-row class="flex-start-center-wrap">
					<el-col :span="24">
						<el-form-item class="margin-bottom-0" label="配料明细:">
							<jk-table border :data="ingredientList" :height="220">
								<vxe-column title="品种" align="left" field="productName" :min-width="100" />
								<vxe-column title="批号" align="left" field="batchCode" :min-width="100" />
							</jk-table>
						</el-form-item>
					</el-col>
					<el-col :span="12">
						<el-form-item class="margin-bottom-0" label="特殊工艺:">
							<jk-table border :data="specialProcessesList" :height="220">
								<vxe-column title="名称" align="left" field="name" :min-width="100" />
								<vxe-column title="数值" align="left" field="value" :min-width="100" />
							</jk-table>
						</el-form-item>
					</el-col>
				</el-row>-->
			</div>
			<div ref="box2" class="flex-between-center margin-bottom-4 margin-top-10">
				<el-alert type="info" :closable="false" show-icon>
					<div class="flex-start-center">
						<div>
							<span>为您找到 </span>
							<span style="font-size: 13px;font-weight: 700;">{{ tableData.length }}</span>
							<span> 张</span>
							<span>工艺单,点击下方的按钮进行选择，当然你也可以选择</span>
						</div>
						<el-button size="mini" type="text" plain @click="onAddBtn">去新建</el-button>
					</div>
				</el-alert>
			</div>
			<div class="technology-task">
				<jk-table :row-style="rowClassName" border :loading="tableLoading" :data="tableData" :height="dialogTableHeight - 20">
					<vxe-column title="工艺单号" align="left" field="code" :width="160">
						<template slot-scope="scope">
							<span class="link-style" @click="onDetailBtn(scope)">{{ scope.row.code }}</span>
						</template>
					</vxe-column>
					<vxe-column title="品种" align="left" field="productName" :min-width="160"></vxe-column>
					<vxe-column title="批号" align="left" field="batchCode" :min-width="140" />
					<vxe-column title="机型" align="left" field="machineModelName" :width="100" />
					<vxe-column title="工序" align="left" field="processName" :width="70" />
					<vxe-column title="状态" align="center" field="operation" :width="90">
						<template slot-scope="scope">
							<jk-common-status :status="scope.row.auditState"></jk-common-status>
						</template>
					</vxe-column>
					<vxe-column title="操作" align="center" field="operation" :width="90">
						<template slot-scope="scope">
							<el-button type="primary" size="mini" @click="onSelectBtn(scope.row)">选择</el-button>
						</template>
					</vxe-column>
				</jk-table>
			</div>
		</el-form>
		<technology-detail-dialog
			:data-id="technologyOrderId"
			:dialog-state="technologyDetailDialogState"
			@on-visible-change="onVisibleChangeOfTechnologyDetailDialog"
		></technology-detail-dialog>
		<add-technology-dialog
			:task-id="ruleForm.id"
			:dialog-state="addTechnologyDialogState"
			@on-visible-change="onVisibleChangeOfAddTechnology"
			@on-confirm="onConfirmBtnOfAddTechnology"
		></add-technology-dialog>
	</jk-dialog>
</template>

<script>
    import calHeight from '/src/mixins/cal-dialog-height';
    import remoteSearchTechnologyOrderInput
        from '../../production/order/components/remote-search-technology-order-input';
    import { spinSpecSheetPage } from '../../../api/technology/order';
    import {
        spinSpecSheetTaskBatchUpdate,
        spinSpecSheetTaskGet,
        spinSpecSheetTaskSubmitAudit,
        spinSpecSheetTaskUpdate
    } from '../../../api/production/xsNotice';
    import technologyDetailDialog from './technology-detail-dialog';
    import addTechnologyDialog from './add-technology-dialog';
    export default {
        components: {
            addTechnologyDialog,
            technologyDetailDialog,
            remoteSearchTechnologyOrderInput
        },
        props: {
            // 页面权限的前缀
            permissionPrefix: {
                type: String,
                default: ''
            },
            dialogState: {
                type: Boolean,
                default: false
            },
            dataId: {
                type: Array,
                default() {
                    return [];
                }
            }
        },
        mixins: [calHeight],
        data() {
            return {
                frontProcessList: ['SM', 'TB', 'MB', 'CS'],
                addTechnologyDialogState: false,
                technologyOrderId: null,
                technologyDetailDialogState: false,
                specialProcessesList: [],
                ingredientList: [],
                tableLoading: false,
                tableData: [],
                showDialog: false,
                showLoading: true,
                confirmBtnLoading: false,
                ruleForm: {
                    id: null,
                    tenPrice: null,
                    productId: null,
                    productCode: '',
                    productName: '',
                    productModels: '',
                    specSheetId: null,
                    specSheetCode: '',
                    machineCode: '',
                    productOrderCode: null,
                    prdNoticeCode: null,
                    productOrder: {}
                },
                rules: {
                    tenPrice: [{ required: true, trigger: 'change' }],
                    specSheetId: [{ required: true, trigger: 'change' }]
                },
                selectItem: {}
            };
        },
        methods: {
            isFront() {
                this.ruleForm.processCode = this.ruleForm.processCode ? this.ruleForm.processCode.toUpperCase() : '';
                return this.frontProcessList.includes(this.ruleForm.processCode);
            },
            onConfirmBtnOfAddTechnology() {
                this.addTechnologyDialogState = false;
                this.getTechnologyListRequest();
            },
            onVisibleChangeOfAddTechnology(e) {
                this.addTechnologyDialogState = e;
            },
            onDetailBtn(scope) {
                this.technologyOrderId = scope.row.id;
                this.technologyDetailDialogState = true;
            },
            onVisibleChangeOfTechnologyDetailDialog(e) {
                this.technologyDetailDialogState = e;
            },
            rowClassName({ row }) {
                if (row.id === this.selectItem.id) {
                    return {
                        backgroundColor: '#19be6b',
                        color: '#fff'
                    };
                }
            },
            onAddBtn() {
                this.addTechnologyDialogState = true;

                // this.$emit('on-visible-change', false);
                // this.$toOtherRouter({
                //     name: 'addTechnology',
                //     query: {
                //         technologyTaskId: this.ruleForm.id
                //     }
                // });
            },
            onSelectBtn(e) {
                this.selectItem = e;
                this.$set(this.ruleForm, 'specSheetId', e.id);
                this.$set(this.ruleForm, 'specSheetCode', e.code);
            },
            onSelectTechnologyOrderChange(e) {
                if (e && Object.keys(e).length) {
                    this.$set(this.ruleForm, 'specSheetId', e.id);
                    this.$set(this.ruleForm, 'specSheetCode', e.code);
                } else {
                    this.$set(this.ruleForm, 'specSheetId', null);
                    this.$set(this.ruleForm, 'specSheetCode', '');
                }
                this.calMachineNum();
            },
            getParamData() {
                const params = JSON.parse(JSON.stringify(this.ruleForm));
                params.typeName = this.scheduleList.find(x => x.id === params.typeId).name;
                return params;
            },
            saveRequest() {
                this.confirmBtnLoading = true;
                const params = {
                    'ids': this.dataId.map(x => x.id),
                    'specSheetId': this.ruleForm.specSheetId,
                    'specSheetCode': this.ruleForm.specSheetCode,
                    'tenPrice': this.ruleForm.tenPrice,
                    'cover': false,
                    'submit': false
                };
                spinSpecSheetTaskBatchUpdate(params).then(res => {
                    if (res.data.status === 200) {
                        this.confirmBtnLoading = false;
                        this.$tipsBar(this, 'save');
                        this.$emit('on-finish');
                    } else if (res.data.status === 202) {
                        this.$confirm(res.data.message, '提示', { type: 'warning' }).then(() => {
                            // 确认覆盖
                            params.cover = true;
                            params.submit = true;
                            spinSpecSheetTaskBatchUpdate(params).then(res => {
                                this.confirmBtnLoading = false;
                                if (res.data.status === 200) {
                                    this.$tipsBar(this, 'save');
                                    this.$emit('on-finish');
                                }
                            });
                        }).catch(() => {});
                    } else {
                        this.confirmBtnLoading = false;
                    }
                });
            },
            onConfirmBtn() {
                this.$refs['ruleForm'].validate(valid => {
                    if (valid) {
                        this.saveRequest();
                    } else {
                        this.$tipsBar(this, 'validator');
                    }
                });
            },
            onVisibleChange(e) {
                this.$emit('on-visible-change', e);
                if (!e) {
                    Object.assign(this.$data, this.$options.data());
                    this.$nextTick(() => {
                        this.$refs['ruleForm'].clearValidate([]);
                        this.$refs.ruleForm.resetFields();
                    });
                }
            },
            getDetailRequest() {
                return spinSpecSheetTaskGet({ id: this.dataId[0].id }).then(res => {
                    if (res.data.status === 200) {
                        if (res.data.res.productOrder && res.data.res.productOrder.specialProcessesList) {
                            this.ruleForm = res.data.res;
                            if (res.data.res.productOrder.coarseSandList) {
                                this.ingredientList = res.data.res.productOrder.coarseSandList;
                                this.specialProcessesList = res.data.res.productOrder.specialProcessesList || [];
                            } else {
                                this.ingredientList = res.data.res.prdNotice.spunYarnBomItemList || [];
                            }
                            this.$set(this.ruleForm, 'tenPrice', res.data.res.prdNotice.tenPrice || null);
                        } else {
                            res.data.res.productOrder = {};
                            res.data.res.productOrder.specialProcessesList = [];
                            this.ruleForm = res.data.res;
                        }
                        this.$nextTick(() => {
                            this.$refs['ruleForm'].clearValidate([]);
                            this.calDialogViewHeight();
                        });
                    }
                });
            },
            getTechnologyListRequest() {
                return spinSpecSheetPage({
                    auditState: 1,
                    productNameOrCode: this.ruleForm.productName
                    // batchCode: this.ruleForm.batchCode
                }).then(res => {
                    if (res.data.status === 200) {
                        this.tableData = res.data.res;
                    }
                });
            },
            async getDependentData() {
                this.showLoading = true;
                if (this.dataId.length) {
                    await this.getDetailRequest();
                    await this.getTechnologyListRequest();
                }
                this.showLoading = false;
            }
        },
        watch: {
            dialogState(newVal) {
                this.showDialog = newVal;
                if (newVal) {
                    this.getDependentData();
                }
            }
        }
    };
</script>
<style>
    .technology-task-form-val {
        color: #515a6e;
        white-space: nowrap;
    }
    .technology-task .vxe-body--row.row-green {
        background-color: #187;
        color: #fff;
    }
</style>
